package io.renren.modules.sp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sp.dao.SpBaseMatchItemGoupRefDao;
import io.renren.modules.sp.dto.SpBaseMatchItemDTO;
import io.renren.modules.sp.entity.SpBaseMatchItemEntity;
import io.renren.modules.sp.entity.SpBaseMatchItemGoupRefEntity;
import io.renren.modules.sp.excel.SpBaseMatchItemExcel;
import io.renren.modules.sp.service.SpBaseMatchItemGoupRefService;
import io.renren.modules.sp.service.SpBaseMatchItemService;
import io.renren.modules.sys.dao.SysDictDataDao;
import io.renren.modules.sys.entity.SysDictDataEntity;
import io.renren.modules.sys.service.SysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
* 赛项
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-21
*/
@RestController
@RequestMapping("sp/spbasematchitem")
@Api(tags="赛项")
public class SpBaseMatchItemController {
    @Autowired
    private SpBaseMatchItemService spBaseMatchItemService;
    @Autowired
    private SysDictDataDao sysDictDataDao;
    @Autowired
    private SpBaseMatchItemGoupRefDao spBaseMatchItemGoupRefDao;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sp:spbasematchitem:page")
    public Result<PageData<SpBaseMatchItemDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<SpBaseMatchItemDTO> page = this.getPage(params);
        return new Result<PageData<SpBaseMatchItemDTO>>().ok(page);
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sp:spbasematchitem:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        //设置分页参数
        params.put(Constant.PAGE, "1");
        params.put(Constant.LIMIT, "10000");
        PageData<SpBaseMatchItemDTO> page = this.getPage(params);
        ExcelUtils.exportExcelToTarget(response, "赛项", "赛项", page.getList(), SpBaseMatchItemExcel.class);
    }
    public PageData<SpBaseMatchItemDTO> getPage(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<SpBaseMatchItemDTO> page = spBaseMatchItemService.page(params);
        // 循环处理成绩
        for (SpBaseMatchItemDTO spBaseMatchItemDTO : page.getList()) {
            String scores = spBaseMatchItemDTO.getScores();
            if(scores != null && !"".equals(scores)){
                String[] split = scores.split(",");
                String scoreLabel = "";
                for (String s : split) {
                    // 查询字典值
                    SysDictDataEntity sysDictDataEntity = sysDictDataDao.selectOne(new QueryWrapper<SysDictDataEntity>().eq("dict_value", s));
                    if(sysDictDataEntity != null){
                        scoreLabel += sysDictDataEntity.getDictLabel() + "、";
                    }
                }
                // 去掉最后一个逗号
                if(scoreLabel.length() > 0){
                    scoreLabel = scoreLabel.substring(0, scoreLabel.length() - 1);
                }
                spBaseMatchItemDTO.setScores(scoreLabel);
            }
            // 查询开设的组别
            List<SpBaseMatchItemGoupRefEntity> groupNames = spBaseMatchItemGoupRefDao.selectList(
                    new QueryWrapper<SpBaseMatchItemGoupRefEntity>().eq("match_item_id", spBaseMatchItemDTO.getId()));
            if(groupNames.size()>0) {
                //循环查字典
                String groupName = "";
                for (SpBaseMatchItemGoupRefEntity groupNameEntity : groupNames) {
                    SysDictDataEntity sysDictDataEntity = sysDictDataDao.selectById(groupNameEntity.getGroupId());
                    if (sysDictDataEntity != null) {
                        groupName += sysDictDataEntity.getDictLabel() + "、";
                    }
                }
                // 去掉最后一个逗号
                if (groupName.length() > 0) {
                    groupName = groupName.substring(0, groupName.length() - 1);
                }
                spBaseMatchItemDTO.setGroups(groupName);
            }else{
                spBaseMatchItemDTO.setGroups("小学组、初中组、高中组");
            }
        }
        return page;
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("sp:spbasematchitem:info")
    public Result<SpBaseMatchItemDTO> get(@PathVariable("id") Long id){
        SpBaseMatchItemDTO data = spBaseMatchItemService.get(id);

        return new Result<SpBaseMatchItemDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sp:spbasematchitem:save")
    public Result save(@RequestBody SpBaseMatchItemDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        spBaseMatchItemService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sp:spbasematchitem:update")
    public Result update(@RequestBody SpBaseMatchItemDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        spBaseMatchItemService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sp:spbasematchitem:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        spBaseMatchItemService.delete(ids);

        return new Result();
    }

    @PostMapping("list")
    public Result<List<SpBaseMatchItemEntity>> list(@ApiIgnore @RequestBody Map<String, Object> params){
        Long matchId = null;
        if(params.get("matchId")  != null){
            matchId = Long.parseLong(params.get("matchId").toString());
        }
        List<SpBaseMatchItemEntity> list = spBaseMatchItemService.listByItemId(matchId);
        return new Result<List<SpBaseMatchItemEntity>>().ok(list);
    }

    @PostMapping("listAll")
    public Result<List<SpBaseMatchItemEntity>> listAll(@ApiIgnore @RequestBody Map<String, Object> params){
        Long matchId = null;
        if(params.get("matchId")  != null){
            matchId = Long.parseLong(params.get("matchId").toString());
        }
        List<SpBaseMatchItemEntity> list = spBaseMatchItemService.listAll(matchId);
        return new Result<List<SpBaseMatchItemEntity>>().ok(list);
    }

}